package by.grsu.transport.service.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import by.grsu.transport.converter.UserConverter;
import by.grsu.transport.model.User;
import by.grsu.transport.persistence.dao.DaoManager;
import by.grsu.transport.persistence.dao.UserDao;
import by.grsu.transport.persistence.dao.base.ConnectionBehavior;
import by.grsu.transport.persistence.dao.base.DaoCommand;
import by.grsu.transport.persistence.entity.UserEntity;
import by.grsu.transport.service.LoginService;

public class LoginServiceImpl implements LoginService {

	private DaoManager daoManager;

	public LoginServiceImpl(DaoManager daoManager) {
		this.daoManager = daoManager;
	}

	private static final Logger logger = Logger
			.getLogger(LoginServiceImpl.class);

	@Override
	public LoginStatus getLoginStatus(final String login, final String password, final HttpServletRequest request) {

		return (LoginStatus) daoManager.command(new DaoCommand() {
			
			@Override
			public Object execute(DaoManager daoManager) {
				LoginStatus target = null;
				try {

					UserDao userDao = daoManager.getDao(UserDao.class);
					UserEntity userEntity = userDao.getUser(login);
					if (userEntity != null) {
						if (userEntity.getPassword().equals(password)) {
							User user = UserConverter.getInstance()
									.entityToModel(userEntity);
							target = LoginStatus.SUCCESS;
							HttpSession session = request.getSession(true);
							session.setAttribute("auth", user);
						} else {
							target = LoginStatus.FAIL;
						}
					}
				} catch (final Exception e) {
					logger.error("Login Exception: " + e.getMessage());
				}
				return target;
			}
		}, ConnectionBehavior.CLOSE);
		
	}

}
